import cv2
import numpy as np

# 利用sift匹配点计算图像相似度，相似度大于某个阈值的两张图片才进行详细的对比
def calc_similarity(image_name1, image_name2):
    image1 = cv2.imread(image_name1)
    image2 = cv2.imread(image_name2)

    sift = cv2.xfeatures2d_SIFT.create()

    # 获取特征点和描述符
    kps1, des1 = sift.detectAndCompute(image1, None)
    kps2, des2 = sift.detectAndCompute(image2, None)

    # Knn计算匹配点
    bf = cv2.BFMatcher(cv2.NORM_L2)
    matches = bf.knnMatch(des1, des2, k=2)
    good_match = []
    TotalDistance = 0
    print(len(matches))
    for m, n in matches:
        if m.distance < 0.9*n.distance:
            TotalDistance += m.distance
            good_match.append(m)
    
    return TotalDistance / len(matches), len(good_match)/len(matches) * 100

if __name__ == "__main__":
    image1_name = "doc_compare1.png"
    image2_name = "doc_compare3.png"
    d, s = calc_similarity(image1_name, image2_name)
    print("Average distance:{:.2f}, Similarity:{:.2f}%".format(d, s))
